/*var a = 1;
function fun1(arg){
	arg = 2;
}
fun1(a);
console.log(a);*/

/*var o = {
	a:1,
	b:2
}
function fun2(arg){
	arg.a = 3;
}
fun2(o);
console.log(o)*/

/*function fun(age){
	if (age>150) {
		throw 'dead'
	}
}
try{
	fun(180);
}catch(e){
	console.log(e);
}*/

/*var http = require('http');
var port = 80;
var ip = '127.0.0.1';
var server = http.createServer(function (request, response) {
	response.statusCode = 200;
	response.setHeader('Content-Type','text/html');
	var fs = require('fs');
	var data = fs.readFileSync('E:/text/nodejs/index.html');	
	response.write(data);
	response.end();
})
server.listen(port);
console.log('Server running at http://%s:%s/',ip,port);*/

var http = require('http');
var fs = require('fs');
var util = require('util');
var siteName = "留言板";
var port = 80;
var ip = '127.0.0.1';
var server = http.createServer(function (request, response) {
	console.log(request.url)
	response.statusCode = 200;
	response.statusMessage = 'bu zhi dao';
	response.setHeader('Content-Type','text/html');

/*	var ext = request.url.substr(-3,3)
	if (ext=="css") {
		response.setHeader('Content-Type','text/css');
	}else if (ext=="jpg") {
		response.setHeader('Content-Type','image/jpeg');
	}*/

	var ext = request.url.substr(request.url.lastIndexOf('.')+1);
	/*console.log(ext);*/
	var exts = {
		'html':'text/html',
		'css':'text/css',
		'jpg':'image/jpeg',
		'js':'text/javascript',
		'png':'image/png'
	}
	if (exts[ext]==null) {
		exts[ext] = 'text/plain'
	}
	response.setHeader('Content-Type',exts[ext]);
	var data = "404";
	try{
		data = fs.readFileSync('.'+request.url,'utf-8')
		data = data.replace(/%title/g,siteName)
		item = fs.readFileSync('data.json','utf-8')
		item = JSON.parse(item)
		var s = "";
		for (var i = 0; i <item.length; i++) {
		    s+='<div class="item">';
			s+='<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>';
			s+='<p>'+item[i].message+'</p></div>'
		}
			data = data.replace(/%main/g,s)
	}catch(e){

	}
	
	/*data = util.format(data,siteName);
	console.log(data);*/

	/*try{
		data = fs.readFile('.'+request.url,function(){
		console.log('2'+new Date().getTime())	
		})
		console.log('1'+new Date().getTime())
		
	}catch(e){
		
	}
	if (data == undefined) {
		data = '404'
	}*/

	response.write(data);
	response.end();
})
server.listen(port);
console.log('Server running at http://%s:%s/',ip,port);